namespace Sustainalytics.Portfolios.Service.Infrastructure
{
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using System.Web.Http.Controllers;

    using Sustainalytics.Claims;
    using Sustainalytics.OAuth.Services.Common;
    using Sustainalytics.Portfolios.Service.Controllers;
    using Sustainalytics.Portfolios.Service.ErrorCodes;
    using Sustainalytics.Portfolios.Service.Utility;
    using Sustainalytics.Utils;

    public class ClaimFilter : AuthorizeAttribute
    {
        private readonly IClaimsChecker _claimsChecker;

        public ClaimFilter(IClaimsChecker claimsChecker)
        {
            this._claimsChecker = claimsChecker;
        }

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var controller = (ApiController)actionContext.ControllerContext.Controller;

            return (controller.GetType() == typeof(SubscribeToPortfolioController))
                       ? this._claimsChecker.ValidateSubscribeToPortfolioClaim(
                           controller,
                           actionContext.Request.Content)
                       : this._claimsChecker.ValidatePortfolioManagementClaim(controller);
            

            return true;
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden, new { ErrorCode = PortfoliosErrorCodes.PortfolioManagementClaimNull });
        }
    }

    public class ProcessClaimsAttribute : AuthorizeAttribute
    {
        private readonly PortfolioUserClaimsProcessor _userClaimsProcessor = new PortfolioUserClaimsProcessor();

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var userClaims = _userClaimsProcessor.GetPortfolioClaims();
            return PortfolioUserClaims.PortfolioClaimsAreValid(userClaims);
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden, new { ErrorCode = PortfoliosErrorCodes.PortfolioManagementClaimNull });
        }
    }
}